package com.simdo.g768.Dialog;

import static com.simdo.g768.MainActivity.device;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.g768.Bean.JsonObject;
import com.g768.MessageControl.MessageController;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.simdo.g768.Adapter.CheckBoxRecyclerviewAdapter;
import com.simdo.g768.Adapter.FreqScanListAdapter;
import com.simdo.g768.Bean.CheckBoxBean;
import com.simdo.g768.Bean.GnbBean;
import com.simdo.g768.Bean.ScanArfcnBean;
import com.simdo.g768.Bean.StepBean;
import com.simdo.g768.File.FileProtocol;
import com.simdo.g768.Listener.ListItemListener;
import com.simdo.g768.MainActivity;
import com.simdo.g768.R;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.PrefUtil;
import com.simdo.g768.Util.Util;
import com.simdo.g768.ZApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class FreqDialog extends Dialog {
	private final LinkedList<ScanArfcnBean> freqList;
	private boolean isStopScan = true;
	private boolean isBandScan = false;
	private int report_type = 0;
	private ProgressDialog progressDialog;
	private final Context mContext;

	public FreqDialog(Context context, LinkedList<ScanArfcnBean> list) {
		super(context, R.style.Theme_B97621);
        this.mContext = context;
        this.freqList = list;
        View view = View.inflate(context, R.layout.pager_freq, null);
		this.setContentView(view);
		this.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
		//this.setCancelable(false);   // 返回键不消失
		//设置dialog大小，这里是一个小赠送，模块好的控件大小设置
		Window window = this.getWindow();
		//window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
		window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
		window.setNavigationBarColor(Color.parseColor("#2A72FF"));
		window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		//StatusBarUtil.setLightStatusBar(window, true);
		WindowManager.LayoutParams lp = window.getAttributes();

		lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
		lp.height = WindowManager.LayoutParams.MATCH_PARENT;
		window.setAttributes(lp);

		readArfcnData();
		initView(view);
    }

	@Override
	public void onBackPressed() {
		if (!isStopScan){
			clickStopFreqScan(true);
			return;
		}
		dismiss();
	}

	private final List<CheckBoxBean> check_box_list = new ArrayList<>();
	private TextView tv_start_scan, tv_freq_state;
	private ImageView iv_anim_freq;
	private FreqScanListAdapter adapter;
	private CheckBoxRecyclerviewAdapter checkBoxAdapter;
	private CheckBox cb_all;
	private TextView tv_freq_title;
	private void initView(View root) {
		tv_freq_title = root.findViewById(R.id.tv_freq_title);
		tv_freq_title.setText(mContext.getString(R.string.arfcn_real));
		RecyclerView list_check_box_nr = root.findViewById(R.id.list_check_box);
		list_check_box_nr.setLayoutManager(new FlexboxLayoutManager(mContext, FlexDirection.ROW, FlexWrap.WRAP));
		checkBoxAdapter = new CheckBoxRecyclerviewAdapter(mContext, check_box_list, new ListItemListener() {
			@Override
			public void onItemClickListener(int position) {
				boolean isAllChecked = true;
				for (CheckBoxBean bean : check_box_list) {
					if (bean.isChecked()) continue;
					isAllChecked = false;
					break;
				}
				cb_all.setChecked(isAllChecked);
			}
		});
		list_check_box_nr.setAdapter(checkBoxAdapter);

		cb_all = root.findViewById(R.id.cb_all);
		cb_all.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				checkBoxAdapter.setChecked(cb_all.isChecked());
			}
		});
		
		root.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!isStopScan){
					clickStopFreqScan(true);
					return;
				}
                dismiss();
			}
		});

		root.findViewById(R.id.freq_setting).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!isStopScan){
					MainActivity.getInstance().showToast(mContext.getString(R.string.in_freq_tip));
					return;
				}
				showFreqSettingDialog(v);
			}
		});

		root.findViewById(R.id.iv_cfg_arfcn).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
                /*if (!isStopScan){
                    MainActivity.getInstance().showToast("扫频中，无法进入设置");
                    return;
                }*/
				showCfgArfcnDialog();
			}
		});

		iv_anim_freq = root.findViewById(R.id.iv_anim_freq);
		iv_anim_freq.setVisibility(View.GONE);
		tv_freq_state = root.findViewById(R.id.tv_freq_state);

		tv_start_scan = root.findViewById(R.id.tv_start_scan);
		tv_start_scan.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (tv_start_scan.getText().toString().equals(mContext.getString(R.string.start_freq))) clickStartFreqScan();
				else clickStopFreqScan(false);
			}
		});

		RecyclerView freq_scan_list = root.findViewById(R.id.freq_scan_list);
		adapter = new FreqScanListAdapter(mContext, freqList);
		freq_scan_list.setLayoutManager(new LinearLayoutManager(mContext));
		freq_scan_list.setAdapter(adapter);
	}

	private void showFreqSettingDialog(View v) {

		View view = LayoutInflater.from(mContext).inflate(R.layout.popup_freq_setting_menu, null);
		final PopupWindow popupWindow = new PopupWindow(view, Util.dp2px(mContext, 16 * 9), Util.dp2px(mContext, 40 * 4), true);
		view.findViewById(R.id.tv_arfcn_real).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				isBandScan = false;
				report_type = 0;
				tv_freq_title.setText(mContext.getString(R.string.arfcn_real));
				popupWindow.dismiss();
			}
		});
		view.findViewById(R.id.tv_arfcn_file).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				isBandScan = false;
				report_type = 1;
				tv_freq_title.setText(mContext.getString(R.string.arfcn_file));
				popupWindow.dismiss();
			}
		});

		view.findViewById(R.id.tv_band_real).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				isBandScan = true;
				report_type = 0;
				tv_freq_title.setText(mContext.getString(R.string.band_real));
				popupWindow.dismiss();
			}
		});
		view.findViewById(R.id.tv_band_file).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				isBandScan = true;
				report_type = 1;
				tv_freq_title.setText(mContext.getString(R.string.band_file));
				popupWindow.dismiss();
			}
		});

		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);

		Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.bg_popup);
		popupWindow.setBackgroundDrawable(drawable);

		popupWindow.showAsDropDown(v, 0, 10);

	}

	private void readArfcnData() {
		AppLog.I("FreqDialog readArfcnData()");
		check_box_list.add(new CheckBoxBean("N41", 1, ""));
		check_box_list.add(new CheckBoxBean("N78", 1, ""));
		check_box_list.add(new CheckBoxBean("B3", 2, ""));
		check_box_list.add(new CheckBoxBean("B1", 3, ""));
		check_box_list.add(new CheckBoxBean("B7", 3, ""));
		check_box_list.add(new CheckBoxBean("B28", 3, ""));
		check_box_list.add(new CheckBoxBean("B40", 4, ""));
		check_box_list.add(new CheckBoxBean("B39", 4, ""));
		check_box_list.add(new CheckBoxBean("B41", 4, ""));
		check_box_list.add(new CheckBoxBean("N1", 3, ""));
		check_box_list.add(new CheckBoxBean("N28", 3, ""));
		check_box_list.add(new CheckBoxBean("N79", 1, ""));
		check_box_list.add(new CheckBoxBean("B8", 2, ""));
		check_box_list.add(new CheckBoxBean("B5", 2, ""));
		check_box_list.add(new CheckBoxBean("B34", 4, ""));

		try {
			StringBuilder sb = new StringBuilder();
			sb.append("FreqDialog readArfcnData:").append("\n");
			for (int i = 0; i < check_box_list.size(); i++) {
				String band = check_box_list.get(i).getText();
				String value = PrefUtil.build().getString(band, "");
				check_box_list.get(i).addAllArfcnList(Util.json2Int(value, band));
				sb.append("band = ").append(band).append(", value = ").append(value);
			}
			AppLog.D(sb.toString());
		} catch (JSONException e) {
			AppLog.E("readArfcnData JSONException e = " + e);
		}
	}

	private void clickStopFreqScan(boolean isBack) {
		AppLog.D("FreqDialog clickStopFreqScan()");
		Dialog dialog = MainActivity.getInstance().createDialog(false);
		View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_confirm, null);
		TextView tv_title = view.findViewById(R.id.tv_title);
		tv_title.setText(R.string.stop_work);
		TextView tv_msg = view.findViewById(R.id.tv_msg);
		tv_msg.setText(R.string.stop_freq_tip);
		view.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				if (device.getWorkState() == GnbBean.State.FREQ_SCAN) MessageController.build().stopFreqScan(device.getId());

				isStopScan = true;
				progressDialog = new ProgressDialog(mContext, R.style.ThemeProgressDialogStyle);
				progressDialog.setTitle(mContext.getString(R.string.wait));
				progressDialog.setMessage(mContext.getString(R.string.freq_stoping));
				progressDialog.show();
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if (progressDialog != null) {
							progressDialog.dismiss();
							progressDialog = null;

							if (device.getWorkState() == GnbBean.State.FREQ_SCAN) {
								device.setWorkState(GnbBean.State.IDLE);
								MainActivity.getInstance().updateSteps(StepBean.State.success, mContext.getString(R.string.freq_stoped));
							}

							setWorkState(false); // 避免命令下发不响应，这里也做一次清除状态
							if (isBack) dismiss();
						}
					}
				}, 8000);

				MainActivity.getInstance().closeDialog(dialog);
			}
		});
		view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MainActivity.getInstance().closeDialog(dialog);
			}
		});
		MainActivity.getInstance().showDialog(dialog, view, false);
	}

	private void clickStartFreqScan() {
		AppLog.D("FreqDialog clickStartFreqScan()");
		if (device == null) {
			MainActivity.getInstance().showToast(mContext.getString(R.string.dev_offline));
			return;
		}
		if (device.getWorkState() != GnbBean.State.IDLE){
			MainActivity.getInstance().showToast(mContext.getString(R.string.dev_busy_tip));
			return;
		}

		double vol = device.getHeartbeat().getDev_info().getVoltage().get(1) / 1000.0;
		if (vol < 1){
		}else if (vol < 16.6) {
			//MainActivity.getInstance().showRemindDialog(mContext.getString(R.string.vol_min_title), mContext.getString(R.string.vol_min_tip));
			//return;
		}

		boolean noCheck = true;
		for (CheckBoxBean bean : check_box_list) {
			if (bean.isChecked()) {
				noCheck = false;
				break;
			}
		}
		if (noCheck){
			MainActivity.getInstance().showToast(mContext.getString(R.string.select_band));
			return;
		}
		freqList.clear();
		device.setWorkState(GnbBean.State.FREQ_SCAN);
		setWorkState(true);
		freqScan();
	}

	private void showCfgArfcnDialog() {
		AppLog.D("FreqDialog showCfgArfcnDialog()");

		CfgArfcnDialog mCfgArfcnDialog = new CfgArfcnDialog(mContext, check_box_list);

		mCfgArfcnDialog.show();
	}

	private void freqScan(){
		if (isBandScan){
			List<Integer> nr_band = new ArrayList<>();
			List<Integer> lte_band = new ArrayList<>();
			List<Integer> gsm_band = new ArrayList<>();
			for (CheckBoxBean bean : check_box_list) {
				if (bean.isChecked()) {
					int band = Integer.parseInt(bean.getText().substring(1));
					if (bean.getText().contains("B")) lte_band.add(band);
					else nr_band.add(band);
				}
			}
			if (nr_band.isEmpty() && lte_band.isEmpty()) {
				MainActivity.getInstance().showToast(mContext.getString(R.string.freq_list_empty));
				setWorkState(false);
				return;
			}
			startFreqScan(lte_band, nr_band, gsm_band);
		}else {
			List<Integer> list = new ArrayList<>();
			for (CheckBoxBean bean : check_box_list) {
				if (bean.isChecked()) list.addAll(bean.getArfcnList());
			}
			if (list.isEmpty()) {
				MainActivity.getInstance().showToast(mContext.getString(R.string.freq_list_empty));
				setWorkState(false);
				return;
			}
			startFreqScan(list);
		}
	}

	private void startFreqScan(List<Integer> lteList, List<Integer> nrList, List<Integer> gsmList){
		String id = device.getId();
		AppLog.D("FreqDialog startFreqScan id = " + id + ", report_type = " + report_type + ", size lteList = " + lteList.size() + ", nrList = " + nrList.size());
		tv_freq_state.setText(mContext.getString(R.string.freq_scanning));
		MessageController.build().startFreqScanByBand(id, report_type, lteList.stream().mapToInt(Integer::intValue).toArray(), nrList.stream().mapToInt(Integer::intValue).toArray(), gsmList.stream().mapToInt(Integer::intValue).toArray());
	}

	private void startFreqScan(List<Integer> list){
		String id = device.getId();
		AppLog.D("FreqDialog startFreqScan id = " + id + ", report_type = " + report_type + ", list size = " + list.size());
		tv_freq_state.setText(mContext.getString(R.string.freq_scanning));
		MessageController.build().startFreqScanByArfcn(id, report_type, list);
	}

	public void onFreqScanRsp(String id, JsonObject rsp) {
		if (rsp != null) {
			switch (rsp.getInt("type")){
				case 2: // 文件上报
					Object zipfile = rsp.getObject("zipfile");
					if (zipfile != null){
						MainActivity.getInstance().showToast(mContext.getString(R.string.scan_ok_get_local));
						MessageController.build().getFile(id, FileProtocol.DIR_Scan, String.valueOf(zipfile));
					}else {
						MainActivity.getInstance().showToast(mContext.getString(R.string.scan_ok_get_local));
					}
					setWorkState(false);
					break;
				case 1: // 数据上报结束
					setWorkState(false);
					break;
				case 0: // 数据上报
					JSONArray jsonArray = rsp.getJSONArray("data");
					try {
						StringBuilder sb = new StringBuilder();
						for (int j = 0; j < jsonArray.length(); j++) {
							JSONObject object = jsonArray.getJSONObject(j);
							int band = object.getInt("band");
							int arfcn = object.getInt("arfcn");
							int pci = object.getInt("pci");
							int pa = object.getInt("offsetPointA");
							int pk = object.getInt("kssb");
							int rsrp = object.getInt("rsrp");
							int priority = object.getInt("priority");
							String tac = object.getString("tac");
							String eci = object.getString("eci");
							JSONArray plmn = object.getJSONArray("plmn");

							int bandwidth = object.getInt("bandwidth");

							sb.append("arfcn = ").append(arfcn).append(", rsrp = ").append(rsrp);
							if (freqList.isEmpty()) {
								freqList.add(new ScanArfcnBean(tac, eci, plmn.toString(), arfcn, band, pci, rsrp, priority, pa, pk, bandwidth));
							} else {
								boolean isAdd = true;
								for (int i = 0; i < freqList.size(); i++) {
									if (freqList.get(i).getDl_arfcn() == arfcn && freqList.get(i).getPci() == pci) {
										isAdd = false;
										freqList.remove(freqList.get(i));
										ScanArfcnBean arfcnBean = new ScanArfcnBean(tac, eci, plmn.toString(), arfcn, band, pci, rsrp, priority, pa, pk, bandwidth);
										if (tac.isEmpty() || eci.isEmpty()) freqList.add(arfcnBean);
										else freqList.add(0, arfcnBean);
										break;
									}
								}
								if (isAdd) {
									ScanArfcnBean arfcnBean = new ScanArfcnBean(tac, eci, plmn.toString(), arfcn, band, pci, rsrp, priority, pa, pk, bandwidth);
									if (tac.isEmpty() || eci.isEmpty()) freqList.add(arfcnBean);
									else freqList.add(0, arfcnBean);
								}
							}
							adapter.notifyDataSetChanged();
						}
						AppLog.I("onFreqScanRsp() isStopScan " + isStopScan + ", result = " + sb);
					} catch (JSONException e) {
						AppLog.E("onFreqScanRsp err = " + e.getMessage());
					}
					break;
			}
		}
	}

	private void setWorkState(boolean isStart) {
		if (isStart) {
			if (isStopScan){
				isStopScan = false;
				tv_start_scan.setText(mContext.getString(R.string.stop_freq));
				tv_start_scan.setBackgroundResource(R.drawable.btn_bg_delete);
				String scanning = mContext.getString(R.string.freq_scanning);
				for (int i = 0; i < 6; i++){
					MainActivity.getInstance().updateProgress(i, scanning,false);
				}
				MainActivity.getInstance().updateSteps(StepBean.State.success, mContext.getString(R.string.start_freq));
				checkBoxAdapter.setEnable(false);
				cb_all.setEnabled(false);

				iv_anim_freq.setVisibility(View.VISIBLE);
				AnimationDrawable drawable = (AnimationDrawable) iv_anim_freq.getDrawable();
				drawable.start();
			}
		} else {
			isStopScan = true;
			tv_freq_state.setText("");
			tv_start_scan.setText(mContext.getString(R.string.start_freq));
			tv_start_scan.setBackgroundResource(R.drawable.btn_bg_ok);
			String idle = mContext.getString(R.string.idle);
			device.setWorkState(GnbBean.State.IDLE);
			for (int i = 0; i < 6; i++){
				MainActivity.getInstance().updateProgress(i, idle,false);
			}
			MainActivity.getInstance().updateSteps(StepBean.State.success, mContext.getString(R.string.freq_stoped));
			checkBoxAdapter.setEnable(true);
			cb_all.setEnabled(true);

			AnimationDrawable drawable = (AnimationDrawable) iv_anim_freq.getDrawable();
			drawable.stop();
			iv_anim_freq.setVisibility(View.GONE);
		}
	}
}
